package com.offcn.uoss.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/thirdparty/v1/admin/oss")
public class OssController {
    @Resource
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.baucket}")
    private String baucket;

    @RequestMapping("/getPolicy")
    public Map<String, String> getPolicy() {
        // host的格式为 bucketname.endpoint
        String host = "https://" + baucket + "." + endpoint;
        //获取当前时间转为字符串类型
        String formDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //用户上传文件时指定的前缀。
        String dir = formDate + "/";

        Map<String, String> respMap = new LinkedHashMap<>();
        try {
            //定义一个时间
            long expireTime = 30;
            //获取当前时间毫秒值在拼上30*1000，表示超时时间
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            //将字符串格式转为时间格式
            Date expiration = new Date(expireEndTime);

            PolicyConditions conditions = new PolicyConditions();
            conditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            conditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, conditions);

            byte[] bytes = postPolicy.getBytes("utf-8");
            String base64String = BinaryUtil.toBase64String(bytes);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            //封装accessid、签名等信息返回
            respMap.put("accessid", accessId);
            respMap.put("policy", base64String);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        }finally {
            ossClient.shutdown();
        }
      return respMap;
    }
}
